package com.lyp.yangxixi.missionmanagerfragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ajguan.library.EasyRefreshLayout;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lyp.activitys.IndependentActivity;
import com.lyp.activitys.NofenpeiCarDetailsActivity;
import com.lyp.activitys.NofenpeiDectionDectilsActivity;
import com.lyp.activitys.NofenpeiIndoorDectilsActivity;
import com.lyp.adapters.NofenpeiAdapter;
import com.lyp.jsonbean.IndependentBean;
import com.lyp.jsonbean.LoginBean;
import com.lyp.jsonbean.NofenpeiBean;
import com.tjl.yangxixis.OriginalFragment;
import com.tjl.yangxixis.R;
import com.tjl.yangxixis.activity.MainActivity;
import com.tjl.yangxixis.api.YangxixiApi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//未分配
public class NoAllotMissionFragment extends OriginalFragment implements View.OnClickListener{

	View v;
	private RecyclerView mRecyclerView;
	private NofenpeiAdapter mAdapter;
	private GridLayoutManager mGridLayoutManager;
	private List<NofenpeiBean.DataBean> mList = new ArrayList<>();
	private LoginBean.DataBean bean;
	private TextView mCounts;
	private EasyRefreshLayout mEasyRefreshLayout;

	// 全选和全不选 by lzh
	public static TextView mAllTask;
	public static CheckBox mCheckbox;

	//定义一个页码为1
	int pages=1;
	private LinearLayout mQx;
	private Button mBtnZ,mBtnP;

	/**
	 * PS:比 HashMap<Integer, Boolean> 性能更高 by lzh
	 */
	private SparseBooleanArray mSparseBooleanArray = new SparseBooleanArray();

	public View createView(LayoutInflater inflater, ViewGroup container,
						   Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v= inflater.inflate(R.layout.fragment_allmission, null,true);
		init();
		return v;
	}

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub
	}

	public void init(){
		bean = ((MainActivity)getActivity()).dataBean;
		mQx = (LinearLayout) v.findViewById(R.id.ll_quanxuan);
		mCheckbox = (CheckBox) v.findViewById(R.id.cb_missionall);
		mAllTask = (TextView) v.findViewById(R.id.tv_missionall);
		mBtnZ = (Button) v.findViewById(R.id.btn_zf);
		mBtnP = (Button) v.findViewById(R.id.btn_pf);
		mQx.setVisibility(View.VISIBLE);
		mCounts = (TextView) v.findViewById(R.id.tv_counts);
		mRecyclerView = (RecyclerView) v.findViewById(R.id.grid_recycler);
		mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
		mRecyclerView.setLayoutManager(mGridLayoutManager);
		mAdapter = new NofenpeiAdapter(mList, mSparseBooleanArray);
		// 实例化 RecyclerView Adapter
		mRecyclerView.setAdapter(mAdapter);
		mAdapter.setOnItemClickListener(new NofenpeiAdapter.MyItemClickListener() {
			@Override
			public void onItemClick(View v, int position) {
				if (bean.getServer_select().equals("车内空气净化服务")) {
					Intent intentcar = new Intent(getActivity(), NofenpeiCarDetailsActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean", mList.get(position));
					bundle.putSerializable("databeans", bean);
					intentcar.putExtra("ids", ids);
					intentcar.putExtras(bundle);
					startActivity(intentcar);

				} else if (bean.getServer_select().equals("第三方检测服务")) {
					Intent intentdection = new Intent(getActivity(), NofenpeiDectionDectilsActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean", mList.get(position));
					bundle.putSerializable("databeans", bean);
					intentdection.putExtra("ids", ids);
					intentdection.putExtras(bundle);
					startActivity(intentdection);

				}
				else if (bean.getServer_select().equals("室内空气净化服务")) {
					Intent intentindoor = new Intent(getActivity(), NofenpeiIndoorDectilsActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean", mList.get(position));
					bundle.putSerializable("databeans", bean);
					intentindoor.putExtra("ids", ids);
					intentindoor.putExtras(bundle);
					startActivity(intentindoor);
				}
			}
		});
		try {
			nofenpeiRefresh(bean.getC_id(),bean.getServer_select(),pages);

		} catch (IOException e) {
			e.printStackTrace();
		}

		mCheckbox.setOnClickListener(this);
		mAllTask.setOnClickListener(this);
		mBtnZ.setOnClickListener(this);
		mBtnP.setOnClickListener(this);

		mEasyRefreshLayout = (EasyRefreshLayout) v.findViewById(R.id.easylayout);
		mEasyRefreshLayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
			@Override
			public void onLoadMore() {
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							nofenpeiLoadMore(bean.getC_id(),bean.getServer_select(),pages);
						} catch (IOException e) {
							e.printStackTrace();
						}
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mEasyRefreshLayout.loadMoreComplete();
							}
						});
					}
				}).start();
			}

			@Override
			public void onRefreshing() {
				new Thread(new Runnable() {
					@Override
					public void run() {
						SystemClock.sleep(1000);
						try {
							nofenpeiRefresh(bean.getC_id(),bean.getServer_select(),pages);
						} catch (IOException e) {
							e.printStackTrace();
						}
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mEasyRefreshLayout.refreshComplete();
							}
						});
					}
				}).start();
			}
		});
	}


	//刷新
	public void nofenpeiRefresh(String c_id,String server_select,int page) throws IOException {
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(YangxixiApi.APP_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.build();
		YangxixiApi github = retrofit.create(YangxixiApi.class);
		Call<NofenpeiBean> call = github.getNoTask(c_id, server_select,page);
		call.enqueue(new Callback<NofenpeiBean>() {
			@Override
			public void onResponse(Call<NofenpeiBean> call, final Response<NofenpeiBean> response) {
				if (response.body().getResult()== 1 ) {
					mCounts.setText(response.body().getCounts());
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mList.clear();
							mList.addAll(response.body().getData());
							mAdapter.notifyDataSetChanged();
							if (response.body().getNext_page() > 0) {
								pages++;
							} else {
								ToastUtils.showShort("没有更多数据了!");
							}
						}
					});
				}else {
					ToastUtils.showShort(response.body().getMessage());
				}
			}
			@Override
			public void onFailure(Call<NofenpeiBean> call, Throwable t) {
				ToastUtils.showShort(t.getMessage());
			}
		});
	}

	//下拉加载
	public void nofenpeiLoadMore(String c_id,String server_select,int page) throws IOException {
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(YangxixiApi.APP_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.build();
		YangxixiApi github = retrofit.create(YangxixiApi.class);
		Call<NofenpeiBean> call = github.getNoTask(c_id, server_select,page);
		call.enqueue(new Callback<NofenpeiBean>() {
			@Override
			public void onResponse(Call<NofenpeiBean> call, final Response<NofenpeiBean> response) {
				if (response.body().getResult()== 1 ) {
					mCounts.setText(response.body().getCounts());
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mList.clear();
							mList.addAll(response.body().getData());
							mAdapter.notifyDataSetChanged();
							if (response.body().getNext_page() >= 1) {
								pages++;
							} else {
								ToastUtils.showShort("没有更多数据了!");
							}
						}
					});
				}else {
					ToastUtils.showShort(response.body().getMessage());
				}
			}
			@Override
			public void onFailure(Call<NofenpeiBean> call, Throwable t) {
				ToastUtils.showShort(t.getMessage());
			}
		});
	}


	String ids = "";
	@Override
	public void onClick(View v) {
		switch (v.getId()){
			case R.id.cb_missionall: // 全选和全不选 by lzh
				String str = mAllTask.getText().toString();
				if ("全选".equals(str)) {
					// 执行全选操作
					for (int i = 0; i < mList.size(); i++) {
						mSparseBooleanArray.put(i, true);
						mAdapter.notifyDataSetChanged();
					}
					// 重新设置文本框的文字
					mAllTask.setText("全不选");
				} else {
					// 执行全不选操作
					for (int i = 0; i < mList.size(); i++) {
						mSparseBooleanArray.put(i, false);
						mAdapter.notifyDataSetChanged();
					}
					// 重新设置文本框的文字
					mAllTask.setText("全选");
				}
				break;
			case R.id.tv_missionall:
				break;
			//自主分配
			case R.id.btn_zf:
				for (int i = 0; i < mSparseBooleanArray.size(); i++) {
					if (mSparseBooleanArray.valueAt(i)) {
						if (i == mSparseBooleanArray.size() - 1) {
							ids += mList.get(mSparseBooleanArray.keyAt(i)).getO_id();
							LogUtils.i("tag",ids+"_dfsfdsf");
						} else {
							ids += mList.get(mSparseBooleanArray.keyAt(i)).getO_id() + ",";
							LogUtils.i("tag",ids+"_00000");
						}
					}
				}
				Intent intentzf = new Intent(getActivity(),IndependentActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("databean",bean);
				bundle.putString("ids", ids);
				intentzf.putExtras(bundle);
				startActivityForResult(intentzf, 0x100);
				break;

			//平均分配
			case R.id.btn_pf:
				for (int i = 0; i < mSparseBooleanArray.size(); i++) {
					if (mSparseBooleanArray.valueAt(i)) {
						if (i == mSparseBooleanArray.size() - 1) {
							ids += mList.get(mSparseBooleanArray.keyAt(i)).getO_id();
						} else {
							ids += mList.get(mSparseBooleanArray.keyAt(i)).getO_id() + ",";
						}
					}
				}
				try {
					avgfenpei(bean.getC_id(), ids);
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
		}
	}

	//平均分配
	private void avgfenpei(String c_id, String ids) throws IOException {
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(YangxixiApi.APP_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.build();
		YangxixiApi github = retrofit.create(YangxixiApi.class);
		Call<IndependentBean> call = github.getAvgIndepen(c_id, ids);
		call.enqueue(new Callback<IndependentBean>() {
			@Override
			public void onResponse(Call<IndependentBean> call, final Response<IndependentBean> response) {
				if (response.body().getResult()== 1 ) {
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							new MaterialDialog.Builder(getActivity())
									.title("分配成功")
									.content("快去做任务吧!")
									.positiveText("确定")
									.canceledOnTouchOutside(false)
									.cancelable(false)
									.onPositive(new MaterialDialog.SingleButtonCallback(){
										@Override
										public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
											mList.clear();
											mAdapter.notifyDataSetChanged();
										}
									})
									.show();
						}
					});
				}else {
					ToastUtils.showShortSafe(response.body().getMessage());
				}
			}
			@Override
			public void onFailure(Call<IndependentBean> call, Throwable t) {
				ToastUtils.showShortSafe(t.getMessage());
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
				case 0x100:
					for(int i = mList.size() - 1; i >= 0; i--){
						if(mSparseBooleanArray.get(i, false)){
							mList.remove(i);
							mSparseBooleanArray.delete(i);
						}
					}
					mSparseBooleanArray.clear();
					ids = "";
					mCounts.setText(String.valueOf(mList.size()));
					mAdapter.notifyDataSetChanged();
			}
		} else if (resultCode == Activity.RESULT_CANCELED) {
			switch (requestCode) {
				case 0x100:
					ids = "";
			}
		}
	}
}
